

const { getClient } = require('./initDbClient')

const tableName = "plugin_info"
const model = {
    pluginId: "string",
    groupId: "string",
    artifactId: "string",
    version: "string",
    pluginInfo: "json",
    private: "boolean",
    extInfo: "json",        // 扩展字段：作为预留字段，用于用户个性化配置控制，包括是否置顶等

}


function initTable(callback, force = false) {
    if (force) {
        sql = `drop table  if exists ${tableName} ; create table ${tableName} 
            ( 
                pluginId varchar(128), 
                groupId varchar(256), 
                artifactId varchar(256),
                version varchar(128),
                private varchar(8),
                pluginInfo text,
                extInfo text,
                gmtCreate varchar(128), 
                gmtModified varchar(128)
            )`
    } else {
        sql = `create table  if not exists ${tableName} 
            ( 
                pluginId varchar(128), 
                groupId varchar(256), 
                artifactId varchar(256),
                version varchar(128),
                private varchar(8),
                pluginInfo text,
                extInfo text,
                gmtCreate varchar(128), 
                gmtModified varchar(128)
            )`
    }
    getClient().createTable(sql, callback)
}

function do2Models(objs) {
    const data = []
    if (objs == null) {
        return data
    }
    for (let obj of objs) {
        data.push(do2Model(obj))
    }
    return data
}

function model2Dos(objs) {
    const data = []
    if (objs == null) {
        return data
    }
    for (let obj of objs) {
        data.push(model2Do(obj))
    }
    return data
}


function do2Model(obj) {
    let model = {}

    Object.keys(obj).forEach(function (key) {
        if (key == "pluginInfo" || key == "extInfo") {
            model[key] = JSON.parse(obj[key])
        } else if (key.startsWith("gmt")) {
            model[key] = new Date(obj[key] * 1000)
        } else if (key == "private") {
            model[key] = obj[key] == "true" ? true : false
        }

        else {
            model[key] = obj[key]
        }
    });
    return model

}

function model2Do(obj) {
    let DO = {}
    Object.keys(obj).forEach(function (key) {
        if (key == "pluginInfo" || key == "extInfo") {
            DO[key] = JSON.stringify(obj[key])
        } else if (key.startsWith("gmt")) {
            model[key] = parseInt(new Date().getTime() / 1000);
        } else if (key == "private") {
            model[key] = obj[key] ? "true" : "false"
        } else {
            DO[key] = obj[key]
        }
    });

    return DO

}

exports.insert = function (model) {
    const obj = model2Do(model)
    const dataItem = []
    const keys = []
    const value = []
    Object.keys(obj).forEach(function (key) {
        keys.push(key)
        if (key.startsWith("gmt")) {
            dataItem.push(obj[key])
            value.push("now()")
        } else {
            dataItem.push(obj[key])
            value.push("?")
        }
    });
    const now = parseInt(new Date().getTime() / 1000);
    keys.push("gmtCreate")
    keys.push("gmtModified")
    value.push("?")
    value.push("?")
    dataItem.push(now)
    dataItem.push(now)

    theKeys = keys.join(",")
    theValue = value.join(",")
    const insertTileSql = `insert into  ${tableName} (${theKeys}) values(${theValue})`;
    initTable(() => {
        getClient().insertData(insertTileSql, [dataItem]);
    })
}


exports.update = function (model) {
    const obj = model2Do(model)


    const pluginId = obj.pluginId
    const pluginInfo = obj.pluginInfo
    const extInfo = obj.extInfo
    const now = parseInt(new Date().getTime() / 1000);
    if (extInfo != null) {
        updateSql = `update ${tableName} set pluginInfo = '${pluginInfo}',extInfo ='${extInfo}' , gmtModified = '${now}' where pluginId = '${pluginId}' `;
    } else {
        updateSql = `update ${tableName} set pluginInfo = '${pluginInfo}', gmtModified = '${now}' where pluginId = '${pluginId}' `;
    }
    initTable(() => {
        getClient().executeSql(updateSql)
    })



}

exports.getPluginInfoByCondition = function (pluginId, groupId, artifactId, callback) {
    let sql = `select * from ${tableName} where 1=1`
    if (pluginId != null) {
        sql = sql + ` and pluginId= '${pluginId}'`
    }
    if (groupId != null) {
        sql = sql + ` and groupId= '${groupId}'`
    }
    if (artifactId != null) {
        sql = sql + ` and artifactId= '${artifactId}'`
    }
    sql = sql + " order by gmtModified desc;"
    initTable(() => {
        getClient().queryData(sql, (data) => {
            callback(do2Models(data))
        })
    })

}



exports.composeModel = function (pluginId, groupId, artifactId, version, private, pluginInfo, extInfo) {
    return {
        pluginId: pluginId,
        groupId: groupId,
        version: version,
        artifactId: artifactId,
        private: private,
        pluginInfo: pluginInfo,
        extInfo: extInfo
    }
}